﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Copad.BusinessCard.BLL;
using Copad.BusinessCard.Model;
using System.Xml.Serialization;
using System.IO;

public partial class SystemConfig : BusinessCardPageBase
{
    GroupBLL groupBLL = new GroupBLL();
    UserBLL userBLL = new UserBLL();
    CardPermissionsBLL permissionsBLL = new CardPermissionsBLL();

    protected WorkTimeManager workTime = null;
    protected List<GroupView> GroupList;
    protected List<UserView> UserList;
    protected long cardID;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadData();
        }
    }

    protected void submit_Click(object sender, EventArgs e)
    {
        string groups = Request["Groups"];
        string users = Request["Users"];

        if (string.IsNullOrEmpty(groups))
        {
            groups = "";
        }
        if (string.IsNullOrEmpty(users))
        {
            users = "";
        }
        var groupArray = groups.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        var userArray = users.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

        long id;
        List<long> groupID = new List<long>();
        foreach (var item in groupArray)
        {
            if (!long.TryParse(item, out id))
            {
                Manager.ShowMessage(this.Message, "提交了错误的时间参数!", null);
                LoadData();
                return;
            }
            groupID.Add(id);
        }

        List<long> userID = new List<long>();
        foreach (var item in userArray)
        {
            if (!long.TryParse(item, out id))
            {
                Manager.ShowMessage(this.Message, "提交了错误的时间参数!", null);
                LoadData();
                return;
            }
            userID.Add(id);
        }
        TimeSpan time;
        List<TimeSpan> beginTime = new List<TimeSpan>();
        List<TimeSpan> endTime = new List<TimeSpan>();
        for (int i = 1; i < 8; i++)
        {
            var beginDay = Request["beginDay" + i];
            if (beginDay == null || !TimeSpan.TryParse(beginDay, out time))
            {
                Manager.ShowMessage(this.Message, "提交了错误的时间参数!", null);
                LoadData();
                return;
            }
            beginTime.Add(time);
            beginDay = Request["endDay" + i];
            if (beginDay == null || !TimeSpan.TryParse(beginDay, out time))
            {
                Manager.ShowMessage(this.Message, "提交了错误的时间参数!", null);
                LoadData();
                return;
            }
            endTime.Add(time);
        }
        workTime = Manager.TimeManager;
        workTime.DeniedGroupID = groupID;
        workTime.DeniedUserID = userID;
        workTime.BeginTime.Clear();
        workTime.EndTime.Clear();
        for (int i = 0; i < 7; i++)
        {
            workTime.BeginTime.Add(beginTime[i].ToString());
            workTime.EndTime.Add(endTime[i].ToString());
        }


        Manager.Configure.IsDebug = !string.IsNullOrEmpty(Request["IsDebug"]);

        try
        {
            Manager.SaveTimeManager();
            Manager.SaveSystemSet();
            Manager.WriteLog(OperationEnum.Config, "用户：" + Manager.CurrentUser.User.Username + " 修改了配置.");
        }
        catch (Exception ex)
        {
            Manager.ShowMessage(this.Message, "保存配置时出错，请重试或联系管理员!", ex);
            Manager.WriteLog(OperationEnum.Exception, "用户：" + Manager.CurrentUser.User.Username + " 保存配置时出错<br/>" + ex.Message + "<br/>" + ex.StackTrace);
        }
        LoadData();
    }

    private void LoadData()
    {
        try
        {
            workTime = Manager.LoadConfig<WorkTimeManager>(Manager.RootPath + "\\work.config");
        }
        catch (Exception ex)
        {
            Manager.ShowMessage(this.Message, "加载登录控制数据失败!", ex);
            Manager.WriteLog(OperationEnum.Exception, "用户：" + Manager.CurrentUser.User.Username + " 加载登录控制数据失败!<br/>" + ex.Message + "<br/>" + ex.StackTrace);
        }

        if (workTime == null)
        {
            workTime = WorkTimeManager.GetDefault();
        }

        var groups = groupBLL.Get();
        groups.RemoveAll(new Predicate<Group>(x => x.Name == Manager.SYSTEM_NAME));
        GroupList = new List<GroupView>();
        groups.ForEach(x =>
        {
            GroupView view = new GroupView { Name = x.Name, ID = x.ID, IsSelected = workTime.DeniedGroupID.Count(w => w == x.ID) > 0 };
            GroupList.Add(view);
        });

        var users = userBLL.GetAllUser();
        for (int i = 0; i < users.Count; i++)
        {
            bool searched = false;
            foreach (var item in users[i].Groups)
            {
                if (item.Name == Manager.SYSTEM_NAME)
                {
                    searched = true;
                    break;
                }
            }
            if (searched)
            {
                users.RemoveAt(i--);
            }
        }

        UserList = new List<UserView>();
        users.ForEach(x =>
        {
            UserView view = new UserView { Username = x.User.Username, ID = x.User.ID, Password = x.User.Password, IsSelected = workTime.DeniedUserID.Count(w => w == x.User.ID) > 0 };
            UserList.Add(view);
        });

    }
}